import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../api/api_service.dart';
import '../../models/post.dart';
import '../../providers/app_state.dart';
import '../../config/app_theme.dart';
import '../community/post_detail_screen.dart';

class FavoritePostsScreen extends StatefulWidget {
  @override
  _FavoritePostsScreenState createState() => _FavoritePostsScreenState();
}

class _FavoritePostsScreenState extends State<FavoritePostsScreen> {
  final ApiService _apiService = ApiService();
  List<Post> _favoritePosts = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadFavoritePosts();
  }

  Future<void> _loadFavoritePosts() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final appState = Provider.of<AppState>(context, listen: false);
      final favoriteIds = appState.favoritePosts;
      
      if (favoriteIds.isEmpty) {
        setState(() {
          _favoritePosts = [];
          _isLoading = false;
        });
        return;
      }

      // 获取所有帖子数据
      final allPosts = await _apiService.getPosts(limit: 100);
      
      // 过滤出收藏的帖子
      final favoritePosts = allPosts.where((post) => favoriteIds.contains(post.id)).toList();
      
      setState(() {
        _favoritePosts = favoritePosts;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      print('Error loading favorite posts: $e');
    }
  }

  void _navigateToPostDetail(Post post) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => PostDetailScreen(post: post),
      ),
    ).then((_) {
      // 回到收藏页面后重新加载数据
      _loadFavoritePosts();
    });
  }

  void _removeFavorite(String postId) {
    Provider.of<AppState>(context, listen: false).toggleFavoritePost(postId);
    setState(() {
      _favoritePosts.removeWhere((post) => post.id == postId);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('收藏的帖子'),
        actions: [
          if (_favoritePosts.isNotEmpty)
            IconButton(
              icon: Icon(Icons.delete_outline),
              onPressed: () {
                _showClearConfirmDialog();
              },
            ),
        ],
      ),
      body: _isLoading
          ? Center(child: CircularProgressIndicator())
          : _favoritePosts.isEmpty
              ? _buildEmptyView()
              : _buildPostsList(),
    );
  }

  Widget _buildEmptyView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.article,
            size: 64,
            color: Colors.grey[400],
          ),
          SizedBox(height: 16),
          Text(
            '暂无收藏的帖子',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
            ),
          ),
          SizedBox(height: 8),
          Text(
            '浏览社区帖子，点击爱心图标收藏你喜欢的帖子',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[500],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPostsList() {
    return ListView.builder(
      padding: EdgeInsets.all(16.0),
      itemCount: _favoritePosts.length,
      itemBuilder: (context, index) {
        final post = _favoritePosts[index];
        return _buildPostCard(post);
      },
    );
  }

  Widget _buildPostCard(Post post) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.0),
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 4,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 帖子头部：用户信息
          Padding(
            padding: const EdgeInsets.all(12.0),
            child: Row(
              children: [
                CircleAvatar(
                  radius: 20,
                  backgroundImage: NetworkImage(post.userAvatar),
                ),
                SizedBox(width: 12.0),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        post.userName,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16.0,
                        ),
                      ),
                      SizedBox(height: 2.0),
                      Text(
                        _formatDate(post.createdAt),
                        style: TextStyle(
                          color: Colors.grey,
                          fontSize: 12.0,
                        ),
                      ),
                    ],
                  ),
                ),
                IconButton(
                  icon: Icon(Icons.favorite, color: Colors.red),
                  onPressed: () => _removeFavorite(post.id),
                ),
              ],
            ),
          ),
          
          // 帖子内容
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  post.title,
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 18.0,
                  ),
                ),
                SizedBox(height: 8.0),
                Text(
                  post.content,
                  maxLines: 3,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(fontSize: 14.0),
                ),
              ],
            ),
          ),
          
          // 帖子图片
          if (post.images.isNotEmpty)
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: _buildPostImages(post),
            ),
          
          // 查看详情按钮
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: ElevatedButton(
              onPressed: () => _navigateToPostDetail(post),
              style: ElevatedButton.styleFrom(
                primary: AppTheme.primaryColor,
                minimumSize: Size(double.infinity, 40),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.0),
                ),
              ),
              child: Text('查看详情'),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPostImages(Post post) {
    if (post.images.length == 1) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(8.0),
        child: Image.network(
          post.images.first,
          height: 200,
          width: double.infinity,
          fit: BoxFit.cover,
        ),
      );
    } else {
      return GridView.count(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        crossAxisCount: post.images.length >= 3 ? 3 : 2,
        mainAxisSpacing: 8.0,
        crossAxisSpacing: 8.0,
        children: post.images.take(6).map((imageUrl) {
          return ClipRRect(
            borderRadius: BorderRadius.circular(8.0),
            child: Image.network(
              imageUrl,
              fit: BoxFit.cover,
            ),
          );
        }).toList(),
      );
    }
  }

  String _formatDate(DateTime date) {
    return '${date.month}月${date.day}日';
  }

  void _showClearConfirmDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('清空收藏'),
          content: Text('确定要清空所有收藏的帖子吗？'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('取消'),
            ),
            TextButton(
              onPressed: () {
                final appState = Provider.of<AppState>(context, listen: false);
                // 逐个移除收藏
                for (var post in _favoritePosts) {
                  appState.toggleFavoritePost(post.id);
                }
                setState(() {
                  _favoritePosts.clear();
                });
                Navigator.of(context).pop();
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('已清空所有收藏的帖子')),
                );
              },
              child: Text('确定'),
            ),
          ],
        );
      },
    );
  }
} 